package com.rocpenghua.ocr;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author pengp
 * @date 2024年03月07日 16:21
 */
@Slf4j
public class TestTess4j {
    public static void main(String[] args) {

        TestTess4j test = new TestTess4j();
        String dataPath = "E:\\soft\\ocr\\tessdata";
        test.doOcr(dataPath, "E:\\soft\\ocr\\OCR-Benchmark-master\\chi-scan-300dpi.jpg", "chi_sim");

    }

    public String doOcr(String dataPath, String filePath, String language) {
        log.info("doOcr start....");
        long startMs = System.currentTimeMillis();
        //Tesseract的代码开始---------------------->>>>
        ITesseract instance = new Tesseract();
        /**
         * 设置目录datapath the tessdata path to set
         * 否则会报Please make sure the TESSDATA_PREFIX environment variable is set to your "tessdata" directory.错误
         */
        instance.setDatapath(dataPath);
        instance.setLanguage(language);
        //instance.setLanguage("eng");//默认，可以不写
//        instance.setLanguage("chi_sim");//设置中文识别
        try (InputStream inStream = new FileInputStream(filePath)) {

            BufferedImage bImage = ImageIO.read(inStream);
            //doOCR也可以传参为File，我这里传的BufferedImage
            String result = instance.doOCR(bImage);
            result = result.replace(" ", "");
            //识别的结果回来可能会带回车，处理掉
            log.info("识别结果：\n" + result);
            return result;
        } catch (IOException | TesseractException e) {
            log.error(e.getMessage(), e);
        }
        log.info("doOcr success. spend time :{} ms.", (System.currentTimeMillis() - startMs));
        return "";
    }
}
